package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.TimeUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.dto.TOrderDto;
import com.kly.service.MemberService;
import com.kly.service.TOrderService;
import com.kly.user.db.dao.*;
import com.kly.user.db.dbo.SumUserMsgDBO;
import com.kly.user.db.dbo.UserDBO;
import com.kly.user.db.entity.IssueUsersConfigEntity;
import com.kly.user.db.entity.IssueUsersEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.db.entity.UserProfileEntity;
import com.kly.user.enums.ConversationType;
import com.kly.user.utils.ServiceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ChatterUsersTask {
    private static Log logger = LogFactory.getLog(FlashChatIssueTask.class);


    @Autowired
    private UserMsgDao userMsgDao;

    @Resource
    private TOrderService tOrderService;

    @Resource
    private UserDao userDao;

    @Resource
    private IssueUsersConfigDao issueUsersConfigDao;

    @Resource
    private UserProfileDao userProfileDao;

    @Resource
    private IssueUsersDao issueUsersDao;

    @Resource
    private MemberService memberService;

    /**
     * 在线用户流量池执行地址
     */
    @NacosValue(value = "${online.list.pool.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    @NacosValue(value = "${chatterUserTaskVersion:1}", autoRefreshed = true)
    private Integer chatterUserTaskVersion;
    @NacosValue(value = "${chatterUserTask.mins:1}", autoRefreshed = true)
    private Integer chatterUserTaskMins;

    @NacosValue(value = "${allowed.all.vip.into.user.list:false}", autoRefreshed = true)
    private Boolean allowedAllVipIntoUserList;


    private String localIP = NetUtil.getLocalhostStr();


    @Scheduled(fixedDelay = 1000 * 60)
    public void run() {
        logger.info("==updateIssueUsersPoolV1 开始任务1==");
        if (chatterUserTaskMins == 1) {
            updateIssueUsersPool(chatterUserTaskMins);
        }
    }

    @Scheduled(fixedDelay = 1000 * 60 * 2)
    public void run2() {
        logger.info("==updateIssueUsersPoolV1 开始任务2==");
        if (chatterUserTaskMins == 2) {
            updateIssueUsersPool(chatterUserTaskMins);
        }
    }

    @Scheduled(fixedDelay = 1000 * 60 * 3)
    public void run3() {
        logger.info("==updateIssueUsersPoolV1 开始任务3==");
        if (chatterUserTaskMins == 3) {
            updateIssueUsersPool(chatterUserTaskMins);
        }
    }

    @Scheduled(fixedDelay = 1000 * 60 * 4)
    public void run4() {
        logger.info("==updateIssueUsersPoolV1 开始任务4==");
        if (chatterUserTaskMins == 4) {
            updateIssueUsersPool(chatterUserTaskMins);
        }
    }

    public void updateIssueUsersPool(int chatterUserTaskMins) {
        logger.info("==updateIssueUsersPool 开始，当前采用的策略版本:{},任务刷新时间:{}==", chatterUserTaskVersion, chatterUserTaskMins);
        try {
            updateIssueUsersPoolV1();
        } catch (Exception e) {
            logger.error("==updateIssueUsersPool 异常 ==", e);
        }

    }

    public void updateIssueUsersPoolV1() {
        logger.info("==updateIssueUsersPoolV1 开始任务==");
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============updateIssueUsersPoolV1 该机器不是任务指定机器, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("deleted", 0);
        List<IssueUsersConfigEntity> issueUsersConfigEntityList = issueUsersConfigDao.selectByParams(map);
        logger.info("==updateIssueUsersPoolV1 开始任务,==");
        if (issueUsersConfigEntityList.isEmpty()) {
            logger.info("==updateIssueUsersPoolV1 找不到对应的配置==");
            return;
        }
        Calendar endTime = Calendar.getInstance();
        Integer endDate = issueUsersConfigEntityList.get(issueUsersConfigEntityList.size() - 1).getEndDate();
        logger.info("==updateIssueUsersPoolV1 找到配置==,endDate:{}", endDate);
        endTime.add(Calendar.SECOND, -1 * endDate);
        endTime.getTime();
        List<UserDBO> userEntityList = userDao.getUserLimitByRegisterDate(endTime.getTime());
        logger.info("==updateIssueUsersPoolV1 获取到所有的在线用户==,size:{},time:{}", userEntityList.size(), endTime.getTime());
        if (userEntityList.isEmpty()) {
            logger.info("==updateIssueUsersPoolV1 找到用户为空==");
            return;
        }

        List<String> targetAllUsers = new ArrayList<>();
        boolean needUpdate = false;
        for (IssueUsersConfigEntity issueUsersConfigEntity : issueUsersConfigEntityList) {
            List<String> targetUsers = getConditionUser(userEntityList, issueUsersConfigEntity);
            targetAllUsers.addAll(targetUsers);
            if (CollectionUtils.isNotEmpty(targetUsers)) {
                needUpdate = true;
            }
        }
        logger.info("==updateIssueUsersPoolV1 当前池子是否需要更新:{}，poolNeedUpdate:{}", needUpdate, targetAllUsers.size());


        logger.info("==updateIssueUsersPoolV1 会员加入到池子的开关==,{}", allowedAllVipIntoUserList);
        //增加一个策略，付费的老用户，全部放进去
        if (allowedAllVipIntoUserList) {
            List<UserEntity> usersByUserTypeAndOnlineStatus = userDao.getUsersByUserTypeAndOnlineStatus(4, 1);
            for (UserEntity byUserTypeAndOnlineStatus : usersByUserTypeAndOnlineStatus) {
                if (targetAllUsers.contains(byUserTypeAndOnlineStatus.getUserCode())) {
                    continue;
                }

                Response<Boolean> booleanResponse = memberService.ifMember(byUserTypeAndOnlineStatus.getUserCode());
                if (booleanResponse != null && booleanResponse.isSuccess()) {
                    logger.info("==updateIssueUsersPoolV1 当前用户是会员==,{}", booleanResponse.getData());
                    Boolean isMember = booleanResponse.getData();
                    if (isMember) {
                        IssueUsersEntity issueUsersEntity = new IssueUsersEntity();
                        issueUsersEntity.setUserCode(byUserTypeAndOnlineStatus.getUserCode());
                        issueUsersEntity.setConfigId(0);
                        issueUsersEntity.setNickName(byUserTypeAndOnlineStatus.getNickName());
                        issueUsersEntity.setGender(byUserTypeAndOnlineStatus.getGender());
                        issueUsersEntity.setAvatarUrl(byUserTypeAndOnlineStatus.getAvatarUrl());
                        issueUsersEntity.setBirthday(byUserTypeAndOnlineStatus.getBirthday());
                        issueUsersEntity.setAge(ageCalculation(byUserTypeAndOnlineStatus.getBirthday()));
                        issueUsersEntity.setUseStatus(0);
                        issueUsersEntity.setRemark("会员用户");
                        UserProfileEntity userProfile = userProfileDao.queryUsersByUserCodeAndType(byUserTypeAndOnlineStatus.getUserCode(), 2);
                        if (userProfile != null) {
                            issueUsersEntity.setAboutMe(userProfile.getAboutMe());
                        }
                        issueUsersDao.insert(issueUsersEntity);
                    }
                }
            }
        }
        logger.info("==updateIssueUsersPoolV1 当前加入到池子的数量==,size:{}", targetAllUsers.size());

        if (needUpdate) {
            //进行删除
            issueUsersDao.deleteByUseStatus(1);

            //更新状态
            issueUsersDao.updateUseStatus(1);
        }


    }

    public static void main(String[] args) {
        Calendar endTime = Calendar.getInstance();
        endTime.add(Calendar.SECOND, -1 * 262800);
        String s = endTime.getTime().toString();
        System.err.println(s);

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime targetMins = now.minusMinutes(262800);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = targetMins.format(formatter);
        System.err.println(format);

        Calendar endTime1 = Calendar.getInstance();
        Integer endDate = 299;
        endTime1.add(Calendar.SECOND, -1 * endDate);
        endTime1.getTime();
        System.out.println(endTime1.getTime().toString());

    }

    /**
     * 判断是否符合
     *
     * @param userEntityList
     * @param issueUsersConfigEntity
     */
    private List<String> getConditionUser(List<UserDBO> userEntityList, IssueUsersConfigEntity issueUsersConfigEntity) {
        List<String> result = new ArrayList<>();
        Calendar beginTime = Calendar.getInstance();
        beginTime.add(Calendar.SECOND, -1 * issueUsersConfigEntity.getBeginDate());
        Calendar endTime = Calendar.getInstance();
        endTime.add(Calendar.SECOND, -1 * issueUsersConfigEntity.getEndDate());
        logger.info("==updateIssueUsersPoolV1 开始判断每个条件下的用户, beginRegister:{},endRegister:{},type:{}", beginTime, endTime, issueUsersConfigEntity.getContentType());
        List<UserDBO> userEntities = userEntityList.stream().filter(o -> o.getRegisterDate().after(endTime.getTime()) && o.getRegisterDate().before(beginTime.getTime())).collect(Collectors.toList());
        logger.info("==updateIssueUsersPoolV1 找到用户数==,size:{}", userEntities.size());
        for (UserDBO userEntity : userEntities) {
            try {
                Boolean shoudAddToPool = checkType(issueUsersConfigEntity.getContentType(), userEntity.getUserCode());
                logger.info("==updateIssueUsersPoolV1 当前用户:{} 是否应该加入到池子==,add:{}", userEntity.getUserCode(), shoudAddToPool);

                if (!shoudAddToPool) {
                    continue;
                }


                IssueUsersEntity issueUsersEntity = new IssueUsersEntity();
                issueUsersEntity.setUserCode(userEntity.getUserCode());
                issueUsersEntity.setConfigId(Math.toIntExact(issueUsersConfigEntity.getId()));
                issueUsersEntity.setNickName(userEntity.getNickName());
                issueUsersEntity.setGender(userEntity.getGender());
                issueUsersEntity.setAvatarUrl(userEntity.getAvatarUrl());
                issueUsersEntity.setBirthday(userEntity.getBirthday());
                issueUsersEntity.setAge(ageCalculation(userEntity.getBirthday()));
                issueUsersEntity.setUseStatus(0);
//            issueUsersEntity.setRemark(issueUsersConfigEntity.getContentType() + "");
                UserProfileEntity userProfile = userProfileDao.queryUsersByUserCodeAndType(userEntity.getUserCode(), 2);
                if (userProfile != null) {
                    issueUsersEntity.setAboutMe(userProfile.getAboutMe());
                }
                issueUsersEntity.setAppCode(userEntity.getAppCode());
                issueUsersEntity.setTrafficType(userEntity.getTrafficType());
                issueUsersEntity.setCustomerCode(userEntity.getCustomerCode());
                issueUsersDao.insert(issueUsersEntity);
                result.add(userEntity.getUserCode());
            } catch (Exception e) {
                logger.info("==updateIssueUsersPoolV1 添加用户异常==,userCode:{}", userEntity.getUserCode(), e);
            }
        }
        return result;
    }


    private Boolean checkType(Integer talkType, String userCode) {
        boolean result = false;
        Map<String, Object> params = ServiceUtils.getParams();
        params.put("fromUserCode", userCode);

        //1破冰会话 2 有效会话 3 深度会话 4 付费
        switch (talkType) {
            case 1:
                params.put("limit", ConversationType.FIRST_CONVERSATION.getSize());
                List<SumUserMsgDBO> userMsgByFromUserCode = userMsgDao.getUserMsgByFromUserCode(params);
                logger.info("==updateIssueUsersPoolV1 确认条件==,type:{},size:{}", talkType, userMsgByFromUserCode.size());
                return userMsgByFromUserCode.isEmpty();
            case 2:
                params.put("limit", ConversationType.EFFECTIVE_CONVERSATIONS.getSize());
                List<SumUserMsgDBO> userMsgByFromUserCode2 = userMsgDao.getUserMsgByFromUserCode(params);
                logger.info("==updateIssueUsersPoolV1 确认条件==,type:{},size:{}", talkType, userMsgByFromUserCode2.size());
                return userMsgByFromUserCode2.isEmpty();
            case 3:
                params.put("limit", ConversationType.DEEP_CONVERSATIONS.getSize());
                List<SumUserMsgDBO> userMsgByFromUserCode3 = userMsgDao.getUserMsgByFromUserCode(params);
                logger.info("==updateIssueUsersPoolV1 确认条件==,type:{},size:{}", talkType, userMsgByFromUserCode3.size());
                return userMsgByFromUserCode3.isEmpty();
            case 4:
                List<TOrderDto> tOrderDtoList = new ArrayList<>();
                Response<List<TOrderDto>> response = tOrderService.queryOrder(userCode);
                if (response.isSuccess()) {
                    List<TOrderDto> tOrders = response.getData();
                    if (tOrders != null) {
                        tOrderDtoList = tOrders.stream().filter(o -> Objects.equals(2, o.getStatus())).collect(Collectors.toList());
                    }
                }

                logger.info("==updateIssueUsersPoolV1 确认条件==,type:{},size:{}", talkType, tOrderDtoList.size());
                return tOrderDtoList.isEmpty();
            default:
                return result;
        }
    }

    private Integer ageCalculation(Date birthday) {
        Integer age = null;
        if (Objects.nonNull(birthday)) {
            try {
                age = TimeUtils.getAge(birthday);
            } catch (Exception e) {
                logger.error("Age calculation error, birthday:{}", birthday);
            }
        }
        return age;
    }

}
